package com.raymond.queue.client.handler;

import com.raymond.queue.client.QueueClient;
import com.raymond.queue.client.msg.MessageManages;
import com.raymond.queue.common.msg.BaseMessage;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;

import java.util.concurrent.ConcurrentHashMap;

/**
 * 业务处理基础类
 *
 * @author :  raymond
 * @version :  V1.0
 * @date :  2021-07-19 11:39
 */
public abstract class BaseBusinessHandler<I extends BaseMessage> extends SimpleChannelInboundHandler<BaseMessage> {

    /**
     * 客户端连接信息
     */
    private QueueClient queueClient;
    /**
     * 消息管理器
     */
    private final ConcurrentHashMap<Integer, MessageManages> msgManager;

    BaseBusinessHandler(Class<? extends BaseMessage> inboundMessageType, QueueClient queueClient) {
        super(inboundMessageType);
        this.queueClient = queueClient;
        this.msgManager = queueClient.getMsgManager();
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, BaseMessage msg) throws Exception {
        @SuppressWarnings("unchecked")
        I iMsg = (I) msg;
        channelRead(ctx, iMsg);
    }

    /**
     * 找到对应的请求通知
     * @param resp 响应
     */
    void responseNotice(BaseMessage resp) {
        MessageManages remove = msgManager.remove(resp.getSequenceId());
        if (remove != null) {
            remove.success(resp);
        } else {
            notRequest(resp);
        }
    }

    /**
     * 当前消息找不到对应的请求
     * @param resp resp
     */
    private void notRequest(BaseMessage resp) {

    }

    /**
     * 读取数据处理
     * @param ctx ctx
     * @param msg 消息对象
     * @throws Exception 异常
     */
    protected abstract void channelRead(ChannelHandlerContext ctx, I msg) throws Exception;

}
